package jjn.round1;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Jiang Jining
 * @since 2023-06-20 22:16
 */
public class LeetCode491_FindSubsequences {
    public List<List<Integer>> findSubsequences(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(nums, new ArrayList<>(), result, 0);
        return result;
    }
    
    private void backtrack(int[] nums, List<Integer> path, List<List<Integer>> result, int startIndex) {
        if (path.size() > 1) {
            result.add(new ArrayList<>(path));
        }
        Set<Integer> set = new HashSet<>();
        for (int i = startIndex; i < nums.length; i++) {
            if (!path.isEmpty() && path.get(path.size() - 1) > nums[i]) {
                continue;
            }
            if (!set.add(nums[i])) {
                continue;
            }
            path.add(nums[i]);
            backtrack(nums, path, result, i + 1);
            path.remove(path.size() - 1);
        }
    }
}
